package com.xln.furns.web;

import com.google.gson.Gson;
import com.xln.furns.entity.Cart;
import com.xln.furns.entity.CartItem;
import com.xln.furns.entity.Furn;
import com.xln.furns.service.FurnService;
import com.xln.furns.service.impl.FurnServiceimpl;
import com.xln.furns.utils.DateUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CartServlet extends BasicServlet {
    FurnService furnService = new FurnServiceimpl();

    protected void shoppingCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Integer id = DateUtils.parseInt(request.getParameter("id"),0);

        Furn furn = furnService.queryFurnById(id);
        CartItem cartItem = new CartItem(furn.getId(),furn.getName(),furn.getPrice(),1,furn.getPrice());

//      500问题所在:空指针异常（cart为null）
//   request.getSession().setAttribute("cart",new Cart());
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if(null == cart){
            request.getSession().setAttribute("cart",new Cart());
            Cart cart1 = (Cart) request.getSession().getAttribute("cart");
            cart1.addItem(cartItem);
            response.sendRedirect(request.getHeader("Referer"));
            return;
        }
//        if (cart != null){
//            cart.addItem(cartItem);
//        }
        cart.addItem(cartItem);

        response.sendRedirect(request.getHeader("Referer"));
//        System.out.printf("cart为:"+cart);

    }
    //购物车优化，异步请求，不用每次添加加载所有页面资源
    protected void shoppingCartAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Integer id = DateUtils.parseInt(request.getParameter("id"),0);

        Furn furn = furnService.queryFurnById(id);
        CartItem cartItem = new CartItem(furn.getId(),furn.getName(),furn.getPrice(),1,furn.getPrice());

//      500问题所在:空指针异常（cart为null）：传入new Cart()【新对象】而没有接受新Session里的对象地址，而下面又用原来的cart对象操作添加。
//   request.getSession().setAttribute("cart",new Cart());
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if(null == cart){
            request.getSession().setAttribute("cart",new Cart());
            cart = (Cart) request.getSession().getAttribute("cart");  /*报错时没有这条语句*/

        }
//        if (cart != null){
//            cart.addItem(cartItem);
//        }
        cart.addItem(cartItem); /*  报错原因 cart为null    */
        Map<String, Object> cartTotalCountMap = new HashMap<>();
        cartTotalCountMap.put("totalCountCart",cart.getTotalCount());
        String cartCountJson = new Gson().toJson(cartTotalCountMap);
        response.getWriter().write(cartCountJson);

        // response.sendRedirect(request.getHeader("Referer"));
//        System.out.printf("cart为:"+cart);

    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer furnId = DateUtils.parseInt(req.getParameter("furnId"),0);
        Integer count = DateUtils.parseInt(req.getParameter("count"),1);
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.updateCount(count,furnId);
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }


    protected void delItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer furnId = DateUtils.parseInt(req.getParameter("furnId"),0);
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.delItem(furnId);
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }

    protected void clearCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart =(Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.clearCart();
        }

        resp.sendRedirect(req.getHeader("Referer"));
    }
}

